import React, { ReactElement, useState, useEffect } from "react";
import Layout from "../core/Layout";
import { Button, Form, Input, message } from "antd";
import { Link } from "react-router-dom";
import { isAuth } from "@/helps/auth";
import { Jwt } from "@/models/auth/dto";
import { createCategory } from "./api/AddCategory";
interface Props {}
const validateMessages = {
  required: "${label}是必填项!",
};
export default function AddCategory(props: Props): ReactElement {
  const [name, setName] = useState<string>("");
  const [form] = Form.useForm();
  const { user, token } = isAuth() as Jwt;
  const onFinish = (value: { name: string }) => {
    console.log(value);
    setName(value.name);
  };
  useEffect(() => {
    async function createCategoryFn() {
      try {
        const response = await createCategory(user._id, name, {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });
        console.log(response);
        message.success(`[${response.data.name}] 分类添加成功`);
      } catch (error) {
        message.error(error.response.data.error);
      }
    }
    if (name) {
      createCategoryFn();
    }
  }, [name]);
  return (
    <Layout title="添加分类" subTitle="">
      <Form form={form} onFinish={onFinish} validateMessages={validateMessages}>
        <Form.Item name="name" label="分类名称" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            添加分类
          </Button>
        </Form.Item>
      </Form>
      <Button>
        <Link to="/admin/dashboard">返回 Dashboard</Link>
      </Button>
    </Layout>
  );
}
